//
//  OrderDetailViewController.swift
//  ZNHXManagement
//
//  Created by 四川中农 on 2018/9/29.
//  Copyright © 2018年 四川中农. All rights reserved.
//

import UIKit
import HandyJSON

class OrderDetailViewController: BaseViewController {
    
    @IBOutlet weak var printButtonHeight: NSLayoutConstraint!
    @IBOutlet weak var printNButton: UIButton!
    @IBOutlet weak var tableView: UITableView!
    
    var bluetoothManager:CBCentralManager!
    
    var  isFirstPrinter = true
    
    var goodsDic:postParameters!
    
    var model : OrdersModel!
    
    var isOpen = false
    
    var id = 0
    
    lazy var alertView : AlertContentView = {
        let view = AlertContentView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.ScreenWidth, height: UIScreen.ScreenHeight))
        view.backClosure = { [weak self] in
            self?.printerDetail()
        }
        
        UIApplication.shared.keyWindow?.addSubview(view)
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.title = "订单详情"
        self.bluetoothManager = CBCentralManager.init(delegate: self, queue: nil)
        self.setRightBarButton(title: "", imageName: "icon_dayin", action: #selector(rightBarMethod), titleColor: "")
        self.getOrderDetail()
    }
    
    @objc func rightBarMethod(){
        let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "PrinterListTableViewController") as! PrinterListTableViewController
        self.navigationController?.pushViewController(ctrl, animated: true)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(false, animated: true)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // MARK:打印小票
    @IBAction func printButtonMethod(_ sender: UIButton) {
        if !self.isOpen {
            PKhud.showText(text: "请先开启手机蓝牙并与打印机配对")
            return
        }
        self.isFirstPrinter = (self.model.isPrint == 1 ? false : true)
        if self.isFirstPrinter {
            HttpRequest.requestData(.post, URLString: Api.orderPrint.rawValue, parameters: ["id":self.id]) { (result) in
                if result["msg"] as! String == "success"{
                    self.alertView.show(withTitle: "确定要打印小票并通知用户提货吗？")
                }else{
                    PKhud.showText(text: result["data"] as! String)
                }
            }
        }else{
            self.alertView.show(withTitle: "此票据已打印过，确定要重新打印吗？")
        }
        
    }
    
    func printerDetail(){
        var model = self.model
        model?.isPrint = 1
        self.model = model
        var goodsArray = [postParameters]()
        for goodsModel in self.model.goods {
            let dic = ["goodsName":goodsModel.name,
                       "spec":goodsModel.spec,
                       "specDesc":goodsModel.specDesc,
                       "num":goodsModel.num]
            goodsArray.append(dic)
        }
        
        goodsDic = ["packageNumber":self.model.packageNumber,
                                       "number":self.model.number,
                                       "createTime":self.model.createTime,
                                       "array":goodsArray]
        Thread.detachNewThreadSelector(#selector(printerClick), toTarget: self, with: nil)
    }
    
    @objc func printerClick(){
        BleManager.share().printer(with: self.goodsDic) {
            Utils.dispatchMainQueue {
                PKhud.showText(text: "请先连接打印机~")
            }
        };
    }
}

extension OrderDetailViewController:CBCentralManagerDelegate{
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        switch central.state {
        case .poweredOn:
            self.isOpen = true
        default:
            self.isOpen = false
        }
    }
}

extension OrderDetailViewController:UITableViewDelegate,UITableViewDataSource{
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.model == nil ? 0 : 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return section == 0 ? 1 : self.model.goods.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "OrderDetailStateTableViewCell") as! OrderDetailStateTableViewCell
            cell.reload(withModel: self.model)
            return cell
        }else{
            let cell = tableView.dequeueReusableCell(withIdentifier: "OrderDetailGoodsTableViewCell") as! OrderDetailGoodsTableViewCell
            cell.reload(withModel: self.model.goods[indexPath.row])
            if indexPath.row == 4 {
                cell.viewLine.isHidden = true
            }else{
                cell.viewLine.isHidden = false
            }
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return indexPath.section == 0 ? 60 : 100
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return section == 0 ? 0.01 : 38
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 1 {
            let header = UIView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.ScreenWidth, height: 38))
            header.backgroundColor = UIColor.white
            
            let view = UIView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.ScreenWidth, height: 10))
            view.backgroundColor = UIColor.backgroundColor
            header.addSubview(view)
            
            var label = Utils.labelWith(frame: CGRect.init(x: 11, y: header.height - 14, width: UIScreen.ScreenWidth/2, height: 14), font: UIFont.boldSystemFont(ofSize: 14), textAlignment: NSTextAlignment.left, textColor: "#000000", text: "包裹清单（共\(self.model.goods.count)种）")
            header.addSubview(label)
            
            label = Utils.labelWith(frame: CGRect.init(x: UIScreen.ScreenWidth/2, y: label.top, width: UIScreen.ScreenWidth/2 - 12, height: 14), font: UIFont.boldSystemFont(ofSize: 13), textAlignment: .right, textColor: "#f7c201", text: "包裹号：" + self.model.packageNumber)
            header.addSubview(label)
            
            let width = self.model.packageNumber.rect(withFont: UIFont.boldSystemFont(ofSize: 13), size: CGSize.init(width: CGFloat.greatestFiniteMagnitude, height: 1)).width
            
            let viewLine = UIView.init(frame: CGRect.init(x: UIScreen.ScreenWidth - 12 - width, y: label.bottom, width: width, height: 1))
            viewLine.backgroundColor = UIColor.init(hexColor: "#f7c201")
            header.addSubview(viewLine)
            
            return header
        }
        return UIView()
    }
    
    func getOrderDetail(){
        PKhud.show()
        HttpRequest.requestData(.post, URLString: Api.orderDetail.rawValue, parameters: ["id":self.id]) { (result) in
            PKhud.hiden()
            if result["msg"] as! String == "success"{
                if let jsonDic = result["data"] as? postParameters{
                    self.model = JSONDeserializer<OrdersModel>.deserializeFrom(dict: jsonDic)
                    self.tableView.reloadData()
                }
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
    
}










